﻿using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Super.Common.Model.Security;
using Super.Domain.Security;
using Super.Web.Filters;
using Super.Web.SecurityClearance;

namespace Super.Web.Controllers
{
    public class SecurityController : Controller
    {
        //
        // GET: /Security/

        [NoCache]
        [AllowAnonymous]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginInformation model, string ReturnURL = null)
        {
            if (ModelState.IsValid)
            {
                SecurityService _securityService = new SecurityService();
                SecurityProvider _securityProvider = new SecurityProvider();

                string domainName;
                string userName = model.UserName;
                if (userName.IndexOf("\\") > 0)
                {
                    // Domain Account
                    string[] userNameSplitted = userName.Split('\\');
                    domainName = userNameSplitted[0];
                    userName = userNameSplitted[1];
                }
                else
                {
                    domainName = null;
                }
                UserDTO userInfo;
                if (!string.IsNullOrEmpty(domainName))
                {
                    using (PrincipalContext principal = new PrincipalContext(ContextType.Domain))
                    {
                        bool isDomainAccountValid = principal.ValidateCredentials(userName, model.Password);

                        userInfo = isDomainAccountValid ? _securityService.FindUser(userName, domainName) : null;
                    }
                }
                else
                {
                    userInfo = _securityProvider.AuthenticateUser(userName, model.Password, domainName);
                }

                if (userInfo != null)
                {
                    _securityProvider.SignIn(userInfo.Id);
                    if (!string.IsNullOrEmpty(ReturnURL) && Url.IsLocalUrl(ReturnURL))
                    {
                        return Redirect(ReturnURL);
                    }
                    else
                    {
                        return RedirectToAction("Dashboard", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid Username or Password");
                }
            }
            else
            {
                ModelState.AddModelError("", "Invalid Username or Password");
            }
            return View(model);
        }
    }
}